<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-button type="primary" @click="showAddRolesDialog">
        添加角色
      </el-button>
      <!-- 角色列表 -->
      <el-table :data="rolesList" stripe border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              v-for="item1 in scope.row.children"
              :key="item1.id"
              class="row1"
            >
              <el-col :span="6">
                <el-tag
                  type="primary"
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                >
                  {{ item1.authName }}
                  <i class="el-icon-caret-right"></i>
                </el-tag>
              </el-col>
              <el-col :span="18">
                <!-- 二级权限 -->
                <el-row
                  v-for="item2 in item1.children"
                  :key="item2.id"
                  class="row2"
                >
                  <el-col :span="6">
                    <el-tag
                      type="danger"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                      <i class="el-icon-caret-right"></i>
                    </el-tag>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限 -->
                    <el-tag
                      class="item3"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoles(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoles(scope.row.id)">
              删除
            </el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配角色权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightsDialogClosed"
    >
      <!-- 树形结构 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        node-key="id"
        default-expand-all=""
        show-checkbox
        :default-checked-keys="defKeys"
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      @close="addRolesDialogClosed"
    >
      角色名称：<el-input v-model="setRoleName" ></el-input> 
      角色描述：<el-input
        v-model="setRoleDes"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRolesDialogVisible"
      width="50%"
    >
      角色名称：<el-input v-model="editRoleName"></el-input> 
      角色描述：<el-input
        v-model="editRoleDes"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      setRightsDialogVisible: false,
      rightsList: [],
      treeProps: {
        children: "children",
        label: "authName",
      },
      defKeys: [],
      roleId: "",
      addRolesDialogVisible: false,
      setRoleName: "",
      setRoleDes: "",
      editRoleName:'',
      editRoleDes:'',
      editRolesDialogVisible:false,
      editRoleId:''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败！");
      this.rolesList = res.data;
      this.$message.success({ duration: 1000, message: "获取角色列表成功！" });
    },
    async removeRightById(val, rightsId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(val);
      console.log(rightsId);
      console.log(confirmResult);

      if (confirmResult !== "confirm")
        return this.$message.warning("取消了删除");
      const { data: res } = await this.$http.delete(
        `roles/${val.id}/rights/${rightsId}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除失败！");
      val.children = res.data;
      this.$message.success("删除成功！");
    },
    async showSetRightDialog(role) {
      this.roleId = role.id;
      this.setRightsDialogVisible = true;
      const { data: res } = await this.$http.get("rights/tree");
      this.rightsList = res.data;
      this.getLeafKeys(role, this.defKeys);
    },
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    setRightsDialogClosed() {
      this.defKeys = [];
    },
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];

      const idStr = keys.join(",");

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) return this.$message.error("分配权限失败");
      this.$message.success("分配权限成功！");
      this.getRolesList();
      this.setRightsDialogVisible = false;
    },
    showAddRolesDialog() {
      this.addRolesDialogVisible = true;
    },
    addRolesDialogClosed() {
      this.setRoleName='',
      this.setRoleDes=''
    },
    async addRole() {
      const { data: res } = await this.$http.post("roles", {
        roleName: this.setRoleName,
        roleDesc: this.setRoleDes,
      });
      if (res.meta.status !== 201) return this.$message.error("添加失败！");
      this.$message.success("添加成功！");
      this.addRolesDialogVisible = false;
      this.getRolesList();
    },
    async editRoles(role){
      const {data:res} = await this.$http.get(`roles/${role.id}`)
      this.editRoleName=res.data.roleName
      this.editRoleDes=res.data.roleDesc
      this.editRoleId = res.data.roleId
      this.editRolesDialogVisible=true
    },
    async confirmEditRole(){
      const {data:res} = await this.$http.put(`roles/${this.editRoleId}`,{roleName:this.editRoleName,roleDesc:this.editRoleDes})
      if (res.meta.status !== 200) return this.$message.error("编辑失败！");
      this.$message.success("编辑成功！");
      this.editRolesDialogVisible=false
      this.getRolesList()
    },
    async deleteRoles(id){
       const deleteConfrirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
        console.log(deleteConfrirmResult);
        if(deleteConfrirmResult!='confirm') return this.$message.warning('取消了删除！')
        const {data:res} = await this.$http.delete(`roles/${id}`)
        if(res.meta.status!==200) return this.$message.error('删除失败！')
        this.$message.success('删除成功！')
        this.getRolesList()
    },
  },
};
</script>

<style lang="less" scoped>
.row1 {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #333;
  border-left: 1px solid #333;
  border-right: 1px solid #333;
}
.row1:nth-child(1) {
  border-top: 1px solid #333;
}
.el-tag {
  margin: 6px;
}
.row2 {
  display: flex;
  align-items: center;
  border-left: 1px solid #333;
  border-bottom: 1px solid #333;
}
.row2:last-child {
  border-bottom: none;
}


</style>